<template>
  <div class="notifyCard">
    <el-card  class="operator-button-card">
      <template #header>
        <div class="flex justify-between items-center">
          <h2 class="operator-button-label">{{ $t('operator.notification') }}</h2>
          <div>
            <el-button
              v-if="isAuth('10400202.MANAGE')"
              type="primary"
              size="small"
              @click="addEmail"
              >{{ $t('common.add') }}</el-button
            >
          </div>
        </div></template
      >
      <div class="notifyTable">
        <el-card
          shadow="never"
          :body-style="{ padding: '0px' }"
          :current-page="pageNo"
          :page-size="pageSize"
          :total="totalCount"
          @current-change="handleCurrentChange"
        >
          <el-table
            :data="emailData"
            style="width: 96%; background-color: white; margin: 0px auto"
            v-loading="loading"
          >
            <el-table-column
              :label="$t('modules.notify.user_name')"
              prop="username"
            >
              <!-- <template v-slot="scope">
                                <div>
                                    <el-tooltip placement="top-start">
                                        <div slot="content" style="max-width:300px;line-height:160%;">
                                            <span>ID:{{ scope.row.keyId }}</span><br>
                                        </div>
                                        <div>
                                            {{ scope.row.username }}
                                        </div>
                                    </el-tooltip>
                                </div>
                            </template> -->
            </el-table-column>
            <el-table-column prop="email" :label="$t('modules.notify.email')" />
            <el-table-column
              :label="$t('modules.notify.web_notify')"
              align="center"
              width="300px"
            >
              <template v-slot="scope">
                <div
                  style="display: inline-block; width: 70px"
                  :class="
                    scope.row.informType == 2 || scope.row.informType == 3
                      ? 'open'
                      : 'close'
                  "
                >
                  <span
                    v-if="
                      scope.row.informType == 2 || scope.row.informType == 3
                    "
                    >{{ $t('modules.notify.open') }}</span
                  >
                  <span
                    v-if="
                      !(scope.row.informType == 2 || scope.row.informType == 3)
                    "
                    >{{ $t('modules.notify.close') }}</span
                  >
                </div>
              </template>
            </el-table-column>
            <!-- 邮箱通知 -->
            <el-table-column
              :label="$t('modules.notify.email_notify')"
              align="center"
              width="300px"
            >
              <template v-slot="scope">
                <div
                  style="display: inline-block; width: 70px"
                  :class="
                    scope.row.informType == 1 || scope.row.informType == 3
                      ? 'open'
                      : 'close'
                  "
                >
                  <span
                    v-if="
                      scope.row.informType == 1 || scope.row.informType == 3
                    "
                    >{{ $t('modules.notify.open') }}</span
                  >
                  <span
                    v-if="
                      !(scope.row.informType == 1 || scope.row.informType == 3)
                    "
                    >{{ $t('modules.notify.close') }}</span
                  >
                </div>
                <!-- <el-button :type="(scope.row.informType==1||scope.row.informType==3)?'success':'danger'" :icon="scope.row.informType==1||scope.row.informType==3?'el-icon-check':'el-icon-close'" circle size="small"></el-button> -->
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('common.creation_time')"
              prop="creDate"
              width="120px"
              align="center"
            >
              <template v-slot="scope">
                <div>
                  <el-tooltip placement="top-start">
                    <template #content>
                      <div style="max-width: 300px; line-height: 160%">
                        <span>{{ scope.row.creTime }}</span
                        ><br /></div
                    ></template>
                    <div>
                      {{ scope.row.creDate }}
                    </div>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              width="100px"
              align="right"
              v-if="isAuth('10400202.MANAGE')"
            >
              <template v-slot="scope">
                <div class="operateIcon" v-if="scope.row.userId !== null">
                  <i
                    class="el-icon-edit"
                    style="margin-top: 10px; margin-right: 15px"
                    @click="editWeb(scope.row)"
                  />
                </div>
                <div class="operateIcon">
                  <i
                    class="el-icon-delete"
                    style="margin-top: 10px; margin-right: 15px"
                    @click="emailDelete(scope.row.reportInformId)"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-card>
    <!-- 添加通知内容 -->
    <el-dialog
      :title="$t('modules.notify.add_notify')"
      v-model="editEmailVisible"
      width="50%"
    >
        <el-form
          ref="emailForm"
          :model="emailForm"
          :rules="rules"
          label-position="top"
        >
          <el-form-item
            :label="$t('modules.notify.notify_type') + ':'"
          >
              <el-checkbox v-model="webNotify">{{
                $t('modules.notify.web_notify')
              }}</el-checkbox>
              <el-checkbox v-model="emailNotify">{{
                $t('modules.notify.email_notify')
              }}</el-checkbox>
          </el-form-item>
          <el-form-item
            :label="$t('modules.notify.email') + ':'"
            prop="email"
            v-if="emailNotify && !webNotify"
          >
            <el-input
              v-model="emailForm.email"
              :disabled="!isAdd"
            />
          </el-form-item>
          <el-form-item
            :label="$t('modules.notify.user_list') + ':'"
            style="margin-bottom: 15px"
            prop=""
          >
            <template>
              <el-checkbox-group
                v-model="value"
                style="max-height: 300px; overflow: auto"
              >
                <div
                  v-for="user in userList"
                  :key="user.userId"
                  @change="
                    (val) => selectUserChange(val, user.userId, user.email)
                  "
                >
                  <el-checkbox
                    :label="user.userId"
                    border
                    :disabled="!user.isShow"
                    >{{ user.name }} - {{ user.email }}</el-checkbox
                  >
                </div>
              </el-checkbox-group>
            </template>
          </el-form-item>
        </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button text @click="cancelDialog">{{
            $t('common.cancel')
          }}</el-button>
          <el-button type="primary" @click="editEmailInfo">{{
            $t('common.confirm')
          }}</el-button>
        </span></template
      >
    </el-dialog>
    <!-- 修改站内通知方式 -->
    <el-dialog
      :title="$t('modules.notify.edit_web')"
      v-model="editWebVisible"
      width="50%"
    >
      <div class="m-center w-10/12">
        <el-form label-width="150px" style="margin-bottom: 10px" :rules="rules">
          <el-form-item
            :label="$t('modules.notify.notify_type') + ':'"
            style="margin-bottom: 10px"
          >
            <template>
              <el-checkbox v-model="editWebNotify">{{
                $t('modules.notify.web_notify')
              }}</el-checkbox>
              <el-checkbox v-model="editEmailNotify">{{
                $t('modules.notify.email_notify')
              }}</el-checkbox>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="editWebVisible = false">{{
            $t('common.cancel')
          }}</el-button>
          <el-button size="small" type="primary" @click="editWebInfo">{{
            $t('common.confirm')
          }}</el-button>
        </span></template
      >
    </el-dialog>
  </div>
</template>

<script>
import {
  getEmail,
  deleteEmails,
  addEmail,
  getEmailDetail,
  editEmail,
  getCurrentUserId,
  getUserPage
} from '@/api/email'
import { toTenYMD, toTime } from '@/utils/index'
// import { getUserPage } from '@/api/user'
import { isAuth } from '@/utils'

export default {
  props: {
    operatorId: {
      require: true,
      type: String,
      default: null
    }
  },
  data() {
    return {
      pageNo: 1,
      pageSize: 5,
      totalCount: undefined,
      loading: false,
      emailData: [], // 存放大厅列表数据
      emailForm: {
        // 增加通知对话框数据绑定
        reportInformId: '',
        email: '',
        sendType: '',
        informType: ''
      },
      userList: [], // 存放该用户所拥有的下属用户列表
      isAdd: false, //判断是否是增加通知界面
      editWebVisible: false, //编辑界面
      editEmailVisible: false, //添加通知内容界面
      webNotify: undefined,
      emailNotify: undefined,
      notifyEditId: undefined, // 需要修改的id
      editWebNotify: undefined,
      editEmailNotify: undefined,
      tempSelect: [], // 存放增加通知对话框中选中的对象
      value: [],
      rules: {
        email: [
          {
            required: true,
            message: 'Email is required',
            trigger: ['change', 'blur']
          },
          {
            type: 'email',
            message: 'Email format error',
            trigger: ['change', 'blur']
          }
        ]
      },
      params: {
        characterCode: 'OPERATOR',
        keyId: this.operatorId
      }
    }
  },
  created() {
    this.getEmailList()
  },
  methods: {
    //获取email list
    isAuth,
    getEmailList() {
      let params = {
        characterCode: 'OPERATOR',
        keyId: this.operatorId,
        pageNo: this.pageNo,
        pageSize: 5
      }
      getEmail(params)
        .then((res) => {
          console.log(res)
          this.totalCount = res.total
          this.emailData = res.list
          for (let i = 0; i < res.list.length; i++) {
            this.emailData[i].creDate = toTenYMD(
              parseInt(this.emailData[i].creTime)
            ).toString()
            this.emailData[i].creTime = toTime(
              parseInt(this.emailData[i].creTime)
            ).toString()
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // 处理分页
    handleCurrentChange(val) {
      this.pageNo = val
      this.getEmailList()
    },
    //删除email
    emailDelete(id) {
      // 加个确认
      this.$confirm(this.$t('tip_content.notify_delete'), '', {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      })
        .then(() => {
          const array = [id]
          deleteEmails(this.params, array)
            .then((res) => {
              console.log(res)
              this.getEmailList()
            })
            .catch((err) => {
              this.$message.error(err.message)
            })
        })
        .catch((e) => {})
    },
    // 获取当前账号下的所有可以被通知的用户
    queryUserPage(data) {
      getUserPage(this.params)
        .then((res) => {
          this.userList = res
          for (let i = 0; i < this.userList.length; i++) {
            this.userList[i]['isShow'] = true
            // 将已经选中的userId禁选
            for (let j = 0; j < data.length; j++) {
              if (data[j].userId === this.userList[i].userId) {
                this.userList[i]['isShow'] = false
              }
            }
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
    //添加通知
    addEmail() {
      this.tempSelect = []
      getCurrentUserId(this.params)
        .then((res) => {
          this.queryUserPage(res)
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
      this.editEmailVisible = true
      this.value = []
      this.tempSelect = []
      this.$nextTick(function () {
        this.isAdd = true
        this.webNotify = false
        this.emailNotify = false
        for (const key in this.emailForm) {
          this.emailForm[key] = ''
        }
      })
    },
    selectUserChange(val, id, email) {
      let result = this.tempSelect.find((item) => {
        return item.userId === id
      })
      // 新加入的输入，需要增加

      if (typeof result === 'undefined') {
        this.tempSelect.push({
          userId: id,
          email: email
        })
      } else {
        // 重复的数据，需要删除

        this.tempSelect = this.tempSelect.filter((item) => item.userId !== id)
      }
    },
    //点击添加通知对话框确定按钮，确定修改
    editEmailInfo() {
      // 0都不通知，1只通知邮箱，2只站内通知，3都通知
      let informType = undefined
      if (this.webNotify === false && this.emailNotify === true) {
        informType = 1
        this.tempSelect.push({
          email: this.emailForm.email
        })
      } else if (this.webNotify === true && this.emailNotify === false) {
        informType = 2
      } else if (this.webNotify === false && this.emailNotify === false) {
        informType = 0
      } else {
        informType = 3
      }
      if ((informType == 0 || informType == 2) && this.tempSelect.length == 0) {
        this.$message.error(
          this.$t('tip_content.check_email_or_check_user_tip')
        )
      } else if (informType == 3 && this.tempSelect.length == 0) {
        this.$message.error(this.$t('tip_content.check_user_tip'))
      } else {
        this.$refs['emailForm'].validate((valid) => {
          if (valid) {
            // 加个确认，增加邮箱
            const data = {
              characterCode: 'OPERATOR',
              keyId: this.operatorId,
              sendType: 0,
              informType: informType,
              userList: this.tempSelect
            }
            this.$confirm(this.$t('tip_content.add_notify'), '', {
              confirmButtonText: this.$t('common.confirm'),
              cancelButtonText: this.$t('common.cancel'),
              type: 'warning'
            })
              .then(() => {
                addEmail(data)
                  .then((res) => {
                    this.getEmailList()
                    this.editEmailVisible = false
                  })
                  .catch((err) => {
                    this.$message.error(err.message)
                  })
              })
              .catch((e) => {})
          }
        })
      }
    },
    // 取消通知对话框界面
    cancelDialog() {
      this.editEmailVisible = false
      this.webNotify = false
      this.emailNotify = false
      if (this.isAdd === false) {
        for (const key in this.emailForm) {
          this.emailForm[key] = ''
        }
      }
    },
    //编辑通知方式,点击进入对话框
    editWeb(detail) {
      this.notifyEditId = detail.reportInformId
      this.editWebNotify = false
      this.editEmailNotify = false
      this.editWebVisible = true
      getEmailDetail(detail.reportInformId, this.params)
        .then((res) => {
          // 判断网站通知类型
          if (res.informType === 1) {
            this.editWebNotify = false
            this.editEmailNotify = true
          } else if (res.informType === 2) {
            this.editWebNotify = true
            this.editEmailNotify = false
          } else if (res.informType === 0) {
            this.editWebNotify = false
            this.editEmailNotify = false
          } else {
            this.editWebNotify = true
            this.editEmailNotify = true
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // 点击编辑对话框确定按钮，确定修改
    editWebInfo() {
      this.$confirm(this.$t('tip_content.edit_notify'), '', {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      })
        .then(() => {
          let informTypeTemp = undefined
          if (this.editWebNotify === false && this.editEmailNotify === true) {
            informTypeTemp = 1
          } else if (
            this.editWebNotify === true &&
            this.editEmailNotify === false
          ) {
            informTypeTemp = 2
          } else if (
            this.editWebNotify === false &&
            this.editEmailNotify === false
          ) {
            informTypeTemp = 0
          } else {
            informTypeTemp = 3
          }
          editEmail(this.notifyEditId, informTypeTemp, this.params)
            .then((res) => {
              this.editWebVisible = false
              this.getEmailList()
            })
            .catch((err) => {
              this.$message.error(err.message)
            })
        })
        .catch((e) => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.l-card {
  margin: 20px 36px;
}

.item {
  display: inline-block;
}

.buttomItem {
  margin-top: 40px;
  float: right;
}

.operateIcon {
  display: inline-block;
  width: 40px;
  color: #2c7be5;
}

.operateIcon :hover {
  color: #484ff3;
  cursor: pointer;
}

.web_right {
  font-size: 19px;
  font-weight: 600;
}

.web_wrong {
  font-size: 30px;
  font-weight: 600;
  position: relative;
  right: 2px;
  width: 23px;
}

.email_right {
  font-size: 19px;
  font-weight: 600;
}

.email_wrong {
  font-size: 30px;
  font-weight: 600;
  position: relative;
  right: 2px;
  width: 23px;
}

.open {
  background-color: #46c89a;
  color: white;
}

.close {
  background-color: #f9fafb;
  color: black;
}
</style>

<style lang="scss">
.notifyCard .el-card__body {
  padding: 0px;
}

.notifyTable .fty-card {
  // margin:0px 20px 0px 20px;
  margin: 0px;
}

.notifyTable .el-table table th.el-table__cell {
  background-color: white;
}
</style>
